//index.js
//获取应用实例
const app = getApp()

Page({
  onShow() {
    var app = getApp();
    app.data.webShowed = true; //标记已经显示过web-view页了
  },
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    url: "",
    shareUrl: null,
    shareTitle: null
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    var that = this;
    console.log(options)
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    var pages = getCurrentPages();
    var currentPage = pages[pages.length - 1];
    var url = '';
    if (!currentPage.options.return_url) {
      url = getApp().globalData.url + `?t=${new Date().getTime()}`
    } else {
      // url = currentPage.options.return_url + '?token=' + currentPage.options.token
      url = decodeURIComponent(currentPage.options.return_url)
      console.log(url)
    }
    that.setData({
      title: "何平窑陶瓷",
      url: url
    });
  },
  onShareAppMessage: function (options) {
    var that = this;
    var return_url = options.webViewUrl;
    var path = '/pages/index/index?return_url=' + encodeURIComponent(that.data.shareUrl ? that.data.shareUrl : return_url);
    var title = that.data.shareTitle ? that.data.shareTitle : that.data.title
    console.log(that.data.shareTitle)
    console.log(that.data.shareUrl)
    this.setData({
      shareUrl: null,
      shareTitle: null
    })
    console.log(that.data.shareTitle)
    console.log(that.data.shareUrl)
    return {
      title: title,
      path: path
    }
  },
  handlePostMessage: function (e) {
    console.log(e)
    let that = this;
    let shareUrl = e.detail.data[e.detail.data.length - 1];
    this.setData({
      shareUrl: JSON.parse(shareUrl).url,
      shareTitle: JSON.parse(shareUrl).title
    })
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})